<template>
  <div class="dynamic_form_item">
    <a-form-item :name="props.question.key">
      <template v-slot:label v-if="props.question.label">
        <label for="">{{ props.question.label }}</label>
        <a-tooltip  v-if="props.question.state.tipText" :key="props.question.label" :title="props.question.state.tipText" >
          <i class="iconfont" :style="{ marginLeft: '8px' }" :class="props.question.state.tipIconClassName"></i>
        </a-tooltip>
      </template>
      <div v-if="props.config?.isView">
        <span v-if="props.question.state.labelKey">{{ showKeyName(props.dataForm, props.question.state.labelKey) }}</span>
        <span v-else>{{ staticView }}</span>
      </div>
      <div v-else>
        <a-form-item-rest>
          <a-checkbox v-if="props.question.type == 'selectAll'" :indeterminate="isIndeterminate" v-model:checked="checkAll" @change="handleCheckAllChange">全选</a-checkbox>
        </a-form-item-rest>
        <a-checkbox-group v-model:value="props.question.value" :disabled="props.question.disabled" @change="handleChecked" :options="props.question.options"> </a-checkbox-group>
      </div>
    </a-form-item>
  </div>
</template>
<script setup lang="ts">
import { Subscription } from 'rxjs';
import { watch, getCurrentInstance, onMounted, onUnmounted, computed } from 'vue';
import { QuestionBase } from '../../../question-base';
import { filter } from 'rxjs/operators';
import { INFOSERVE } from '@/mixins/subject/subject-types';
import { showKeyName } from '@/components/public-template/publicMethod';

// import { getDictionaryList } from "@/utils/dictionary";
// import dictionary from "@/filters/dictionary";

//subject变量
let $subscribeSub: Subscription;

let checkAll: boolean = false;
let isIndeterminate: boolean = false;

const { proxy }: any = getCurrentInstance();
let props = defineProps<{ question: QuestionBase<any>; formData: any; config?: any; dataForm: any; }>();
const emit = defineEmits(['update:formData']);
watch(
  () => props.question.value,
  (val) => {
    emit('update:formData', val);
  },
  { flush: 'sync' }
);

onMounted(() => {
  subWatch();
  if (props.question.state.url) {
    getData();
  }
});

//解绑
onUnmounted(() => {
  if ($subscribeSub != undefined) {
    $subscribeSub.unsubscribe();
  }
  proxy.$NotificationFormSub.clearParams();
});
//静态数据
const staticView = computed(() => {
  if (props.question.value || props.question.value == 0) {
    let params = props.question.value;
    let data = props.question.options.filter((res) => [...params].includes(String(res.value)));

    if (!!data) {
      return data.map((e) => e.label).join(',');
    }
  }
});

const init = (list) => {
    props.question.options = list.map((res: any) => ({
      ...res,
      label: res[props.question.state.keyName || 'name'],
      value: res[props.question.state.keyValue || 'id']
    }));
    handleChecked(props.question.value)
    
};

//监听动态表单数据完成
const subWatch = () => {
  $subscribeSub = proxy.$NotificationFormSub
    .getParams()
    .pipe(filter((res: any) => res !== 0))
    .subscribe((item: any) => {
      try {
        if (item.key === INFOSERVE) {
          //数据都全部都到了
          if (item.value) {
            console.log('自己',item.value[props.question.key]);
            if(props.question.type === 'options'){
              init(props.question.state.options);
            }else{
              handleChecked(props.question.value)
            }
          }
        }
      } catch (error) {}
    });
};

//获取数据
function getData() {
  if( props.question.state.url ){
    let param: any = props.question.state.params || {};
    proxy.$Http.api(props.question.state.url, param, props.question.state.protType ? props.question.state.protType : 'get').then((res: any) => {
      if( res && res.data ){
        init(res.data);
      }
    });
  }
}

//全选
function handleCheckAllChange(e: any) {
  props.question.value = e.target.checked ? props.question.options.map((res: any) => (typeof res == 'string' ? res : res.value)) : [];
  isIndeterminate = false;
  handleChecked(props.question.value)
}

function handleChecked(val: any) {
  let checkedCount = props.question.value.length;
  checkAll = checkedCount === props.question.options.length;
  isIndeterminate = checkedCount > 0 && checkedCount < props.question.options.length;
  if( props.question.state.selectParams ){  //开启自定义数据
    props.question.state.selectValue =  props.question.options.filter(res=> val.includes(res[props.question.state.keyValue || 'id']) );
    console.log('多选框',props.question.state.selectValue);
  }
}
</script>

<style lang="less" scoped>
@import url('./input-checkbox.component.less');
</style>
